package com.lenovo.smarttraffic.util;

import android.content.Context;

import com.android.volley.RequestQueue;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.lenovo.smarttraffic.InitApp;

import org.json.JSONException;
import org.json.JSONObject;

/***
 * @author Cyzen
 * @date 2020/10/24
 */
public class HttpUtil {

    static RequestQueue requestQueue = Volley.newRequestQueue(InitApp.getContext());
    static JSONObject jsonObject = new JSONObject();

    static {
        String user = InitApp.getContext().getSharedPreferences("login", Context.MODE_PRIVATE).getString("user", "admin");
        try {
            jsonObject.put("UserName", user);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    public interface ICallBack {
        void success(JSONObject jsonObject) throws JSONException;

        void error(String msg);
    }

    public static void add(String k, Object v) {
        try {
            if (jsonObject.has(k)) {
                jsonObject.remove(k);
            }
            jsonObject.put(k, v);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    public static void post(String url, ICallBack callBack) {
        requestQueue.add(new JsonObjectRequest(1, "http://192.168.1.118:8088/transportservice/action/" + url, jsonObject, jsonObject -> {
            try {
                callBack.success(jsonObject);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }, volleyError -> callBack.error(volleyError.getMessage())));
    }

    public static void postold(String url, ICallBack callBack) {
        requestQueue.add(new JsonObjectRequest(1, "http://192.168.1.118:8080/api/v2/" + url, jsonObject, jsonObject -> {
            try {
                callBack.success(jsonObject);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }, volleyError -> callBack.error(volleyError.getMessage())));
    }
}
